import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { MallSpecEntity } from '../entity/spec';
import { CoolCommException } from '@cool-midway/core';
import { MallGoodsService } from './goods';

/**
 * 商品规格
 */
@Provide()
export class MallSpecService extends BaseService {
  @InjectEntityModel(MallSpecEntity)
  mallSpecEntity: Repository<MallSpecEntity>;

  @Inject()
  mallGoodsService: MallGoodsService;

  async getSpecByGoodsId(goodsId: number) {
    await this.mallGoodsService.checkGoodsExists(goodsId);
    return this.mallSpecEntity.findBy({ goodsId: goodsId });
  }

  /**
   * 检查规格是否存在
   * @param specId
   */
  async checkSpecExists(specId: number) {
    const spec = await this.mallSpecEntity.findOneBy({ id: specId });
    if (!spec) {
      throw new CoolCommException('规格不存在');
    }
  }
}
